package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.domain.Show;
import cn.wolfcode.enums.NoticeLevelEnum;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.NoticeQueryObject;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.util.RequirePermission;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller
@RequestMapping("/notice")
public class NoticeController {

    @Autowired
    private INoticeService noticeService;
    @Autowired
    private EmployeeMapper employeeMapper;


    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") NoticeQueryObject qo){
        //用来判断是否为管理员,不是则不显示是否发布,添加和编辑按钮
        Employee currentUser = UserContext.getCurrentUser();
        model.addAttribute("currentUser",currentUser);

        PageInfo<Notice> pageInfo = noticeService.query(currentUser,qo);
        model.addAttribute("pageInfo", pageInfo);

        NoticeLevelEnum[] enums = NoticeLevelEnum.values();
        model.addAttribute("enums",enums);

        return "notice/list";
    }

    @RequestMapping("/show")
    public String show(@ModelAttribute("show") Show show){
        Employee currentUser = UserContext.getCurrentUser();
        show.setEmpName(currentUser.getName());
        noticeService.updateRelation(currentUser.getId(),show.getNoticeId());

        //保存完关系表以后,再查询一次未读的条数并保存到session中
        int count = employeeMapper.selectUnRead(currentUser.getId());
        currentUser.setUnReadCount(count);
        UserContext.setCurrentUser(currentUser);
        return "notice/show";
    }

    @RequestMapping("/issue")
    @ResponseBody
    public JsonResult issue(Long notId,Boolean issue){
        noticeService.updateIssueById(notId,issue);
        return new JsonResult();
    }

    @RequestMapping("/saveOrUpdate")
    @RequirePermission(name = "公告新增/编辑",expression = "notice:saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Notice notice){
        Employee currentUser = UserContext.getCurrentUser();
        notice.setCreateEmp(currentUser);
        if (notice.getId() != null) {
            noticeService.update(notice);
        }else {
            notice.setCreateTime(new Date());
            noticeService.save(notice);
            //新增了一个公告的同时也保存到关系表里(管理员)
            noticeService.saveRelation(currentUser.getId(),notice.getId(),false);
        }
        return new JsonResult();
    }
}
